<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use App\Console\Commands\WdtClient;

// 批量同步查询库存同步  5min
// 执行命令：php artisan sync:ApiGoodsStockChangeQuery
// 接口描述：获取变化后的旺店通ERP可销库存，并同步至enc平台店铺,注："查询同步库存"与"库存同步回写"两个接口配合使用，完成"库存同步"，仅支持自有/其他平台店铺
// 文档: https://open.wangdian.cn/open/apidoc/doc?path=api_goods_stock_change_query.php
// 示例数据: {"code":0,"message":"OK","stock_change_list":[{"rec_id":"4827486","shop_id":"192","goods_id":"127","spec_id":"","sync_stock":127,"goods_no":"EN2841","spec_no":"EN2841_瓶_60粒","erp_spec_type":"1","erp_spec_id":"311","stock_change_count":"0"}],"current_count":50}
class SyncApiGoodsStockChangeQuery extends Command
{
    protected $signature = 'sync:ApiGoodsStockChangeQuery';
    protected $description = '批量同步查询库存同步并回写';

    public function handle()
    {
        Log::info('同步任务SyncApiGoodsStockChangeQuery', ['开始同步goods物流信息到旺店通']);
        $sid = config('services.wdt.sid');
        $appkey = config('services.wdt.appkey');
        $secret = config('services.wdt.secret');
        $shopNo = config('services.wdt.shopNo');
        $url = config('services.wdt.url') . 'api_goods_stock_change_query.php';

        $c = new WdtClient($sid, $appkey, $secret, $url);

        // 1. 查询所有上架商品ID
//        $goodsList = DB::table('goods')->select(['id'])->get();
        $goodsList = DB::table('goods')->where('status', 1)->select(['id'])->get();
        $total = $goodsList->count();
        $this->info('查询同步查询库存同步并回写 goods上架商品总数: ' . $total);
        $goodsArr = $goodsList->pluck('id')->toArray();
        $batchSize = 2000;
        $requestSize = 100;
        $batches = array_chunk($goodsArr, $batchSize);

        foreach ($batches as $batch) {
            // 每2000条为一批，再分100条一组处理
            $subBatches = array_chunk($batch, $requestSize);
            foreach ($subBatches as $ids) {
                // 这里只是本地分批处理，实际请求旺店通接口还是用limit参数
                $c->putApiParam('limit', $requestSize); // 100~2000
                $c->putApiParam('shop_no', $shopNo);
                Log::info('请求旺店通参数', ['limit' => $requestSize, 'shop_no' => $shopNo]);
                $result = $c->wdtOpenApi();
                //示例数据测试
//                $result = '{"code":0,"message":"OK","stock_change_list":[{"rec_id":"4827486","shop_id":"192","goods_id":"127","spec_id":"","sync_stock":127,"goods_no":"EN2841","spec_no":"EN2841_瓶_60粒","erp_spec_type":"1","erp_spec_id":"311","stock_change_count":"0"}],"current_count":50}';
                Log::info('旺店通商品查询同步查询库存同步并回写查询结果', [$result]);
                $data = json_decode($result, true);
                if (empty($data['stock_change_list'])) {
                    break; // 没有更多待同步数据
                }
                foreach ($data['stock_change_list'] as $item) {
                    // 只处理本地分批的商品ID，提升性能
                    if (!in_array($item['goods_id'], $ids)) {
                        continue;
                    }
                    $sync_stock =  $item['sync_stock'] ?? 0;
                    DB::table('goods')->where('id', $item['goods_id'])->update([
                        'erp_spec_type' => $item['erp_spec_type'] ?? null,
                        'erp_spec_id' => $item['erp_spec_id'] ?? null,
                        'shop_id' => $item['shop_id'] ?? null,
                        'rec_id' => $item['rec_id'] ?? null,
                        'goods_sale_num' => $sync_stock,
                        'goods_total_num' => $sync_stock,
                        // 你可以同步 sync_stock 等字段
                    ]);
                }
                // 你还需要调用 api_goods_stock_change_ack.php 回写同步状态，否则下次还会拉到这些数据
            }
        }
        $this->info('查询同步查询库存同步并回写完毕');
    }
} 